﻿@page "/change-password"
@using System.ComponentModel.DataAnnotations
@inject NavigationManager NavigationManager
@inject IHttpClientFactory HttpClientFactory
@inject IJSRuntime JSRuntime

<div class="change-password-container">
    <div class="change-password-box">
        <div class="logo">
            <img src="/logo.png" alt="Logo" class="logo-image" />
        </div>
        <h2 class="change-password-title">修改密码</h2>

        <EditForm Model="@passwordForm" OnValidSubmit="HandleChangePassword">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="form-group">
                <label for="email">邮箱</label>
                <InputText @bind-Value="passwordForm.Email" id="email" class="form-control custom-input" placeholder="请输入注册邮箱" />
                <ValidationMessage For="@(() => passwordForm.Email)" />
            </div>

            <div class="form-group">
                <label for="oldPassword">原密码</label>
                <InputText @bind-Value="passwordForm.OldPassword" id="oldPassword" type="password" class="form-control custom-input" placeholder="请输入当前密码" />
                <ValidationMessage For="@(() => passwordForm.OldPassword)" />
            </div>

            <div class="form-group">
                <label for="newPassword">新密码</label>
                <InputText @bind-Value="passwordForm.NewPassword" id="newPassword" type="password" class="form-control custom-input" placeholder="请输入新密码" />
                <ValidationMessage For="@(() => passwordForm.NewPassword)" />
            </div>

            <div class="form-group">
                <label for="confirmPassword">确认新密码</label>
                <InputText @bind-Value="passwordForm.ConfirmPassword" id="confirmPassword" type="password" class="form-control custom-input" placeholder="请再次输入新密码" />
                <ValidationMessage For="@(() => passwordForm.ConfirmPassword)" />
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-success submit-btn" disabled="@loading">
                    @if (loading)
                    {
                        <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                        <span>处理中...</span>
                    }
                    else
                    {
                        <span>确认修改</span>
                    }
                </button>
            </div>

            <div class="action-links">
                <a href="/login" class="action-link">返回登录</a>
            </div>
        </EditForm>
    </div>
</div>

@code {
    private ChangePasswordModel passwordForm = new ChangePasswordModel();
    private bool loading = false;

    public class ChangePasswordModel
    {
        [Required(ErrorMessage = "请输入邮箱")]
        [EmailAddress(ErrorMessage = "请输入有效的邮箱地址")]
        public string Email { get; set; }

        [Required(ErrorMessage = "请输入当前密码")]
        public string OldPassword { get; set; }

        [Required(ErrorMessage = "请输入新密码")]
        [MinLength(6, ErrorMessage = "密码长度不能少于6位")]
        public string NewPassword { get; set; }

        [Required(ErrorMessage = "请再次输入新密码")]
        [CustomValidation(typeof(ChangePasswordModel), "ValidateConfirmPassword")]
        public string ConfirmPassword { get; set; }

        public static ValidationResult ValidateConfirmPassword(string confirmPassword, ValidationContext context)
        {
            var model = (ChangePasswordModel)context.ObjectInstance;
            return confirmPassword == model.NewPassword
                ? ValidationResult.Success
                : new ValidationResult("两次输入的密码不一致");
        }
    }

    private async Task HandleChangePassword()
    {
        loading = true;

        try
        {
            var httpClient = HttpClientFactory.CreateClient("Api");

            //调用修改密码接口
            var response = await httpClient.PostAsJsonAsync("/api/user/changePwd", new
            {
                email = passwordForm.Email,
                current_password = passwordForm.OldPassword,
                new_password = passwordForm.NewPassword
            });

            var ResponseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"changePwd API 返回: {ResponseContent}");

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<ChangePasswordResponse>();

                if (result?.Success == true)
                {
                    await JSRuntime.InvokeVoidAsync("alert", "密码修改成功！");
                    NavigationManager.NavigateTo("/login");
                }
            }
            else
            {
                var errorResponse = await response.Content.ReadFromJsonAsync<ErrorResponse>();
                var errorMessage = response.StatusCode switch
                {
                    System.Net.HttpStatusCode.BadRequest =>
                        errorResponse?.Message?.Contains("长度不足") == true
                            ? "新密码长度至少为6个字符"
                            : "请检查输入信息是否正确",
                    System.Net.HttpStatusCode.Unauthorized => "当前密码不正确",
                    System.Net.HttpStatusCode.NotFound => "用户不存在或账户未激活",
                    System.Net.HttpStatusCode.InternalServerError => "服务器错误，请稍后重试",
                    _ => "修改失败，请稍后重试"
                };

                await JSRuntime.InvokeVoidAsync("alert", errorMessage);
            }
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", "网络错误，请检查网络连接");
            Console.WriteLine(ex.Message);
        }
        finally
        {
            loading = false;
        }
    }

    public class ChangePasswordResponse
    {
        public bool Success { get; set; }
    }

    public class ErrorResponse
    {
        public string Message { get; set; }
    }
}

<style>
    .change-password-container {
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
        background-color: #f0f2f5;
        background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    }

    .change-password-box {
        width: 100%;
        max-width: 450px;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        border: none;
        background-color: rgba(255, 255, 255, 0.95);
    }

    .logo {
        text-align: center;
        margin-bottom: 20px;
    }

    .logo-image {
        height: 70px;
        width: auto;
        max-width: 100%;
        object-fit: contain;
        border-radius: 40px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .change-password-title {
        text-align: center;
        color: #2c3e50;
        margin-bottom: 30px;
        font-weight: 600;
        font-size: 22px;
        letter-spacing: 0.5px;
    }

    .form-group {
        margin-bottom: 20px;
    }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #606266;
            font-size: 14px;
        }

    .custom-input {
        border-radius: 8px;
        height: 44px;
        line-height: 44px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
        width: 100%;
    }

        .custom-input:focus {
            border-color: #409eff;
            outline: none;
        }

    .submit-btn {
        width: 100%;
        margin-top: 10px;
        height: 44px;
        font-size: 16px;
        border-radius: 8px;
        background-color: #67c23a;
        border-color: #67c23a;
        transition: all 0.3s;
        color: white;
        border: none;
        cursor: pointer;
    }

        .submit-btn:hover {
            background-color: #85ce61;
            border-color: #85ce61;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
        }

        .submit-btn:disabled {
            background-color: #b3e19d;
            cursor: not-allowed;
        }

    .action-links {
        display: flex;
        justify-content: center;
        margin-top: 20px;
    }

    .action-link {
        color: #409eff;
        font-size: 14px;
        text-decoration: none;
    }

        .action-link:hover {
            color: #66b1ff;
            text-decoration: underline;
        }
</style>